﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api;
using MeTalker.Aide.Mode;
using MeTalker.Aide.data;
using Top.Api.Domain;

namespace MeTalker.Aide.Forms
{
    internal class TaobaoHelper
    {
        /// <summary>
        /// 等待买家付款
        /// </summary>
        internal readonly static string WAIT_BUYER_PAY = "WAIT_BUYER_PAY";

        /// <summary>
        /// 卖家已发货
        /// </summary>
        internal readonly static string WAIT_BUYER_CONFIRM_GOODS = "WAIT_BUYER_CONFIRM_GOODS";//（）

        /// <summary>
        /// 买家已付款
        /// </summary>
        internal readonly static string WAIT_SELLER_SEND_GOODS = "WAIT_SELLER_SEND_GOODS";//（），
        /// <summary>
        /// 交易成功
        /// </summary>
        internal readonly static string TRADE_FINISHED = "TRADE_FINISHED";
        /// <summary>
        /// 交易关闭
        /// </summary>
        internal readonly static string TRADE_CLOSED = "TRADE_CLOSED";
        /// <summary>
        /// 交易被淘宝关闭
        /// </summary>
        internal readonly static string TRADE_CLOSED_BY_TAOBAO = "TRADE_CLOSED_BY_TAOBAO";
        /// <summary>
        /// 没有创建外部交易（支付宝交易）
        /// </summary>
        internal readonly static string TRADE_NO_CREATE_PAY = "TRADE_NO_CREATE_PAY";

        internal string appkey;
        internal string appstr;
        internal string sessionKey;
        Account account;
        int tids = 1;
        internal ItemsListGetResponse GoodsItemsList { get; private set; }
        internal ItemsGetResponse ItemsGetResponseList { get; private set; }
        internal TaobaoHelper(string accountId, string appkey, string appstr, string sessionKey)
        {
            this.appkey = appkey;
            this.appstr = appstr;
            this.sessionKey = sessionKey;
            Init();
        }
        internal TaobaoHelper(Account account)
            : this(account.AccountId, account.AppKey, account.AppSecret,account.TopSession)
        {
            this.account = account;
        }
        void Init()
        {
            try
            {
                GoodsItemsList = SerializerFactory.DeserializeFile<ItemsListGetResponse>(FileFactory.FILE_NAME_GOODS_LIST_ITEM) as ItemsListGetResponse;
            }
            catch { }
        }

        private ITopClient GetClient()
        {
            return new DefaultTopClient(UtilHelper.TAOBAO_API_URL, appkey, appstr);
        }

        internal static ITopClient GetSystemClient()
        {
            return new DefaultTopClient(UtilHelper.TAOBAO_API_URL, "12376452", "9d94cdfb3632126fc819e8997ff78152");
        }

        /// <summary>
        /// 刷新链接
        /// </summary>
        internal void QueryItem()
        {
            try
            {
                ITopClient client = GetClient();
                ItemsGetRequest req = new ItemsGetRequest()
                {                    
                    Fields = "num_iid,title,nick,pic_url,cid,price,type,delist_time,post_fee,score,volume",
                    Nicks = account.AccountId
                };
                ItemsGetResponseList = client.Execute(req, sessionKey);

                if (!ItemsGetResponseList.IsError)
                {
                    string numi = "";
                    GoodsItemsList = new ItemsListGetResponse();
                    GoodsItemsList.Items = new List<Item>();
                    int items = ItemsGetResponseList.Items.Count;
                    for (int i = 0; i < items;i++ )
                    {
                        if (i % 20 == 0 && i != 0)
                        {
                            numi += ItemsGetResponseList.Items[i].NumIid + ",";
                            ItemsListGetResponse temp = FindDetailGoodsInfo(numi);
                            numi = "";
                            if (temp != null)
                            {
                                foreach (var item in temp.Items)
                                {
                                    GoodsItemsList.Items.Add(item);
                                }
                            }
                        }
                    }
                    //foreach (var d in ItemsGetResponseList.Items)
                    //{
                    //    numi += d.NumIid + ",";
                    //   ItemsListGetResponse temp = FindDetailGoodsInfo(numi);
                    //}
                    
                    if (GoodsItemsList != null)
                    {
                        SerializerFactory.SerializeFile<ItemsListGetResponse>(GoodsItemsList, FileFactory.FILE_NAME_GOODS_LIST_ITEM);
                    }
                }
            }
            catch (Exception ex){
                if (UtilHelper.DEBUG) {
                    MuchInfo.Logs.MILog.Error("查链", ex);
                }
            }
        }

        ItemsListGetResponse FindDetailGoodsInfo(string numIids)
        {
            ITopClient client = GetClient();

            ItemsListGetRequest req = new ItemsListGetRequest()
            {
                NumIids = numIids,
                Fields = "price,detail_url,num_iid,title,nick"
            };

           return client.Execute(req, sessionKey);
            //if (GoodsItemsList != null && !GoodsItemsList.IsError)
            //{
            //    SerializerFactory.SerializeFile<ItemsListGetResponse>(GoodsItemsList, FileFactory.FILE_NAME_GOODS_LIST_ITEM);
            //}
        }

        internal bool AddMemo(long tid,long flag, string memo)
        {
            try
            {
                ITopClient client = this.GetClient();
                TradeMemoAddRequest req = new TradeMemoAddRequest();
                req.Tid = tid;
                req.Memo = memo;
                req.Flag = flag;
                TradeMemoAddResponse response = client.Execute(req, sessionKey);
                return !response.IsError;
            }
            catch {
                return false;
            }
        }

        internal bool UpdateMemo(long tid, long flag, bool reset, string memo)
        {
            try
            {
                ITopClient client = this.GetClient();
                TradeMemoUpdateRequest req = new TradeMemoUpdateRequest()
                {
                    Tid = tid,
                    Memo = memo,
                    Flag = flag,
                    Reset = reset
                };
                TradeMemoUpdateResponse response = client.Execute(req, sessionKey);
                return !response.IsError;
            }
            catch
            {
                return false;
            }
        }

       

        internal TradeFullinfoGetResponse FindOrderMemo(string buyer_nick)
        {
            try
            {
                ITopClient client = GetClient();
                TradesSoldGetRequest req = new TradesSoldGetRequest()
                {
                    Fields = "seller_memo,seller_nick,buyer_nick,buyer_message,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type",
                    BuyerNick = buyer_nick,
                };
                TradesSoldGetResponse response = client.Execute(req, sessionKey);
                if (!response.IsError)
                {
                    var ds = from temp in response.Trades where temp.BuyerNick.Equals(buyer_nick) orderby DateTime.Parse(temp.Created) descending select temp;
                    Trade trade =  ds.FirstOrDefault();
                    if (trade != null)
                    {
                        return FindOrderFull(trade.Tid);
                    }
                }
            }
            catch { }
            return null;
        }

        /// <summary>
        /// 交易订单帐务查询 核对邮址
        /// </summary>
        /// <param name="buyer_nick">买家呢称的客户</param>
        internal string FindOrderZipCode(string buyer_nick)
        {
            try
            {
                ITopClient client = GetClient();
                TradesSoldGetRequest req = new TradesSoldGetRequest()
                {
                    Fields = "seller_nick,buyer_nick,buyer_message,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type",
                };
                TradesSoldGetResponse response = client.Execute(req, sessionKey);
                if (!response.IsError)
                {
                    var ds = from temp in response.Trades where temp.BuyerNick.Equals(buyer_nick) orderby DateTime.Parse(temp.Created) descending select temp;
                    Trade order = ds.FirstOrDefault();
                    if (order != null)
                    {
                        string msg = "收件人:" + order.ReceiverName + System.Environment.NewLine +
                            "地址:" + order.ReceiverState + " " + order.ReceiverCity + " " + order.ReceiverDistrict + " " + order.ReceiverAddress + System.Environment.NewLine +
                            "邮编:" + order.ReceiverZip + System.Environment.NewLine +
                            "手机:" + order.ReceiverMobile + System.Environment.NewLine +
                            "电话:" + order.ReceiverPhone + System.Environment.NewLine;
                        TradeFullinfoGetResponse resp = null;
                        if (DataFactory.SystemConfig.IsCheckCustomMsg)
                        {
                            resp = FindOrderFull(order.Tid);
                            msg += Environment.NewLine + "您的留言:" + resp.Trade.BuyerMessage;
                        }
                        if (DataFactory.SystemConfig.IsBillHeader)
                        {
                            if (resp == null)
                                resp = FindOrderFull(order.Tid);
                            msg += Environment.NewLine + "您的发票抬头:" + resp.Trade.InvoiceName;
                        }
                        if (DataFactory.SystemConfig.IsCheckCustomMsg)
                        {
                            foreach (Order temp in order.Orders)
                            {
                                msg += Environment.NewLine + "商品属性:" + temp.SkuPropertiesName;
                            }
                        }
                        return msg;
                    }
                }
            }
            catch { }
            return string.Empty;
        }

        /// <summary>
        /// 按时间段查询单据
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        internal TradesSoldGetResponse FindOrder(DateTime startTime, DateTime endTime)
        {
            try
            {
                ITopClient client = GetClient();
                TradesSoldGetRequest req = new TradesSoldGetRequest()
                {
                    Fields = "seller_name,num,seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type",
                    StartCreated = startTime,
                    EndCreated = endTime,
                };
                return client.Execute(req, sessionKey);
            }
            catch { }
            return null;
        }

       internal string FindOrderTrack(string nick)
        {
            try
            {
                ITopClient client = GetClient();
                TradesSoldGetRequest req = new TradesSoldGetRequest()
                {
                    Fields = "seller_nick,buyer_nick,buyer_message,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type",
                     BuyerNick = nick
                };
                TradesSoldGetResponse response = client.Execute(req, sessionKey);
                if (!response.IsError)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Trade trade in response.Trades)
                    {
                        if (trade.BuyerNick.Equals(nick)) {
                            LogisticsTraceSearchResponse respTrace = LogisticsTraceSearch(trade.Tid, account.AccountId);
                            sb.AppendLine("物流公司:"+respTrace.CompanyName);
                            sb.AppendLine("单号:"+respTrace.Tid);
                            sb.AppendLine("状态:"+respTrace.Status);
                            foreach (TransitStepInfo info in respTrace.TraceList)
                            {
                                sb.AppendLine("时间:" + info.StatusTime + "位置:" + info.StatusDesc);
                            }
                        }
                    }
                    return sb.ToString();
                }
            }
            catch { }
            return string.Empty;
        }

       internal LogisticsTraceSearchResponse LogisticsTraceSearch(long tid, string nick)
       {
           ITopClient client = GetClient();
           LogisticsTraceSearchRequest req = new LogisticsTraceSearchRequest()
           {
               Tid = tid,
               SellerNick = nick
           };
           return client.Execute(req, sessionKey);
       }

        /// <summary>
        /// 交易订单帐务查询
        /// </summary>
        /// <param name="buyer_nick">买家呢称的客户</param>
        internal string FindOrder(string buyer_nick)
        {
            try
            {
                ITopClient client = GetClient();
                TradesSoldGetRequest req = new TradesSoldGetRequest()
                {
                    Fields = "seller_nick,buyer_nick,buyer_message,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type",
                };

                TradesSoldGetResponse response = client.Execute(req, sessionKey);
                if (!response.IsError)
                {
                    string msg = string.Empty;
                    foreach (var order in response.Trades)
                    {
                        if (order.BuyerNick.Equals(buyer_nick))
                        {
                            msg +=
                                    "收件人:" + order.ReceiverName + System.Environment.NewLine +
                                    "  地址:" + order.ReceiverState + " " + order.ReceiverCity + " " + order.ReceiverDistrict + " " + order.ReceiverAddress + System.Environment.NewLine +
                                    "  邮编:" + order.ReceiverZip + System.Environment.NewLine +
                                    "  手机:" + order.ReceiverMobile + System.Environment.NewLine +
                                    "  电话:" + order.ReceiverPhone + System.Environment.NewLine;
                        }
                    }
                    return msg;
                }
            }
            catch { }
            return string.Empty;
        }


        internal TradeFullinfoGetResponse FindOrderFull(long tid)
        {
            ITopClient client = GetClient();
            TradeFullinfoGetRequest req = new TradeFullinfoGetRequest()
            {
                Fields = "invoice_name,seller_memo,buyer_memo,buyer_message,seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type",
                Tid = tid
            };
            return client.Execute(req, sessionKey);
        }


        internal TradeGetResponse FindOrderTradeMemo(string buyer_nick)
        {
            try
            {
                ITopClient client = GetClient();
                TradesSoldGetRequest req = new TradesSoldGetRequest()
                {
                    Fields = "seller_memo,seller_nick,buyer_nick,buyer_message,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type",
                    BuyerNick = buyer_nick,
                };
                TradesSoldGetResponse response = client.Execute(req, sessionKey);
                if (!response.IsError)
                {
                    var ds = from temp in response.Trades where temp.BuyerNick.Equals(buyer_nick) orderby DateTime.Parse(temp.Created) descending select temp;
                    Trade trade = ds.FirstOrDefault();
                    if (trade != null)
                    {
                        return FindOrderTrade(trade.Tid);
                    }
                }
            }
            catch { }
            return null;
        }

        internal TradeGetResponse FindOrderTrade(long tid)
        {
            ITopClient client = GetClient();
            TradeGetRequest req = new TradeGetRequest()
            {
                Fields = "seller_memo,buyer_memo,buyer_message,seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type",
                Tid = tid
            };
            return client.Execute(req, sessionKey);
        }
    }
}